﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class MemberController : ApiController
    {
			static readonly  IRepository<Member> mRepo = new MemberRepository();

			public IEnumerable<Member> GetAllMembers()
			{
				return mRepo.GetAll();
			}

			public Member GetMemeber(int id)
			{
				var found = mRepo.Get(id);
				if (found == null)
				{
					throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
				}
				return found;
			}

			public IEnumerable<Member> GetMembersByLastName(string lastName)
			{
				return mRepo.GetAll().Where(
					m => string.Equals(m.LastName, lastName, StringComparison.OrdinalIgnoreCase));
			}

			public HttpResponseMessage PostMember(Member item)
			{
				item = mRepo.Add(item);
				var response = Request.CreateResponse<Member>(HttpStatusCode.Created, item);

				string uri = Url.Link("DefaultApi", new { id = item.Id });
				response.Headers.Location = new Uri(uri);
				return response;
			}

			public void PutMember(int id, Member member)
			{
				member.Id = id;
				if (!mRepo.Update(member))
				{
					throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
				}
			}

			public HttpResponseMessage DeleteProduct(int id)
			{
				mRepo.Remove(id);
				return new HttpResponseMessage(HttpStatusCode.NoContent);
			}
    }

}
